/*
 * Copyright (c) 2016 zhangcm. All Rights Reserved.
 */
package com.deram.ctin.dependencies.serv.component;

import com.deram.ctin.common.bean.Code;
import com.deram.ctin.common.bean.Error;
import com.deram.ctin.common.error.BusinessException;
import com.google.gson.Gson;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * @author zhangcm
 * @version 1.0, 2017/8/30
 */
@Component
public class ServErrorDecoder implements ErrorDecoder {

    private final Logger logger = LoggerFactory.getLogger(ServErrorDecoder.class);

    public Exception decode(String methodKey, Response response) {
        Gson gson = new Gson();
        try {
            Error error = gson.fromJson(response.body().asReader(), Error.class);
            logger.error(MessageFormat.format("调用{0}服务异常", error.getPath()));
            if(BusinessException.class.getName().equals(error.getException())){
                Code code = gson.fromJson(error.getMessage(), Code.class);
                return new BusinessException(code);
            } else {
                return new BusinessException("服务异常，请稍后重试");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
